package com.leenmvc.core.utils.redis;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Component
public class RedisUtil {

    @Autowired
    private JedisPool jedisPool;

    public String get(String key){
        Jedis jedis = null;
        String value = null;
        try {
            jedis = jedisPool.getResource();
            value = jedis.get(key);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            jedis.close();
        }
        return value;
    }

    public void set(String key,String value){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.set(key,value);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            jedis.close();
        }
    }

    public void set(String key,String value,int second){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.set(key,value);
            jedis.expire(key,second);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            jedis.close();
        }
    }

    public Long incr(String key){
        Jedis jedis = null;
        Long incr = null;
        try {
            jedis = jedisPool.getResource();
            incr = jedis.incr(key);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            jedis.close();
        }
        return incr;
    }

    /**
     * 获取redis的key
     * @param table  表名
     * @param id     表的唯一ID
     * @param filed  字段名
     * @return
     */
    public String getKeyName(String table,Long id,String filed){
        return new StringBuilder(table).append(":").append(id).append(":").append(filed).toString();
    }


}
